//
//  WebSocketManager.m
//  滴滴卡
//
//  Created by powerlong on 15-9-14.
//  Copyright (c) 2015年 kimi. All rights reserved.
//


#define ChatTypeChat  1
#define ChatTypeGroupChat  2

#define ChatContentTypeText  3

#define ChatPackTypeLogin  50
//#define ChatPackTypeLoginAckSuccess  51
//#define ChatPackTypeLoginAckError  52
//
//#define ChatPackTypeMessage  6
//#define ChatPackTypeMessageAck  5

//#define ChatPackTypeSystemMessage  7

#define ChatPackTypePing  90
#define ChatPackTypePong  91

#define ChatPackTypeMessageSetRead 500
#define MessageType 1

#import "WebSocketManager.h"
#import "SystemDeviceTool.h"
#import "SLLoanMessageModel.h"
#import "AppDelegate.h"

@interface WebSocketManager()

@property (assign , nonatomic) BOOL isBackgournd;

@property (strong , nonatomic) NSMutableDictionary * msgCompleteBlocks;

@end

@implementation WebSocketManager

+ (WebSocketManager*)shareInstance{
    static dispatch_once_t pred = 0;
    __strong static WebSocketManager *_sharedObject = nil;
    dispatch_once(&pred, ^{
        _sharedObject = [[self alloc] init];
    });

    return _sharedObject;
}

- (id)init
{
    self = [super init];
    if (self) {
        self.recivers = [NSMutableArray<WebSocketManagerReciver> array];
        self.msgCompleteBlocks = [NSMutableDictionary dictionary];
        self.isBackgournd = NO;
        [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(socketNeeedPing) userInfo:nil repeats:YES];
        // app启动或者app从后台进入前台都会调用这个方法
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
//        // app从后台进入前台都会调用这个方法
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
//        // 添加检测app进入后台的观察者
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterBackground) name: UIApplicationDidEnterBackgroundNotification object:nil];
//        // 添加检测 从活动状态进入非活动状态
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive) name: UIApplicationWillResignActiveNotification object:nil];
//        // 添加检测 程序被杀死时调用
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillTerminat) name: UIApplicationWillTerminateNotification object:nil];
    }
    return self;
}

- (void)appWillEnterForeground{
}
- (void)appEnterBackground{
}
- (void)appWillTerminat{
}
- (void)appBecomeActive{
    self.isBackgournd = NO;
    if ([UserLocal isLogin]) {
        [self startWebSocket];
    }
}
- (void)appWillResignActive{
//    self.isBackgournd = YES;
//    [self setSocketClose];
}
- (void)startWebSocket{
    if (!_webSocket)
    {
        _webSocket.delegate = nil;
        [_webSocket close];
        NSString *urlStr = [NSString stringWithFormat:@"%@%@",@"ws://120.220.43.57:8009/person/app/websocket?macid=",[SystemDeviceTool getUUID]];
        NSLog(@"%@",urlStr);
        _webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
        _webSocket.delegate = self;
        [_webSocket open];
    }
    if ([UserLocal isLogin]) {
        NSMutableDictionary * paramSocket = [NSMutableDictionary dictionary];
        paramSocket[@"macId"] = [SystemDeviceTool getUUID];
        paramSocket[@"userId"] =[[UserLocal sharedInstance] currentUserInfo].phone;
        paramSocket[@"flag"] = @(0);
        [[PLRequestManage sharedInstance] httpRequestWithUrl:WEBSOCKETWITH(url_loginWebsocket) Type:RequestPost parameters:paramSocket completeHandle:^(id  _Nullable responseObject, NSError *error) {
            if (!error) {
            }else{
                
            }
        }];
    }else{
        NSMutableDictionary * paramSocket = [NSMutableDictionary dictionary];
        paramSocket[@"macId"] = [SystemDeviceTool getUUID];
        paramSocket[@"userId"] =[[UserLocal sharedInstance] currentUserInfo].phone;
        paramSocket[@"flag"] = @(1);
        [[PLRequestManage sharedInstance] httpRequestWithUrl:WEBSOCKETWITH(url_loginWebsocket) Type:RequestPost parameters:paramSocket completeHandle:^(id  _Nullable responseObject, NSError *error) {
            if (!error) {
            }else{
            }
        }];
    }
}
- (void)setSocketClose{
    if (_webSocket.readyState == SR_OPEN) {
        [_webSocket close];
        debugLog(@"socket will close");
    }
}
- (void)setSocketOpen{
    if (_webSocket) {
        debugLog(@"socket closed");
        [_webSocket close];
    }
    _webSocket = nil;
    [self startWebSocket];
}
- (SRReadyState)getSocketStatue{
    return [_webSocket readyState];
}

- (void)socketNeeedPing
{
    if (_webSocket.readyState == SR_OPEN){
        @try {
//            NSMutableDictionary * pingPack = [NSMutableDictionary dictionary];
//            [pingPack setObject:@(ChatPackTypePing) forKey:@"packType"];
            [self.webSocket send:@""];
        }
        @catch (NSException *exception) {}
        @finally {}
    }
}

#pragma mark - WebSocket Delegate
- (void)webSocketDidOpen:(SRWebSocket *)webSocket{
    DLog(@"Websocket Connected");
}

- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error{
    DLog(@":( Websocket Failed With Error %@", error);
    if (_webSocket.readyState == SR_OPEN) {
        [_webSocket close];
    }
    _webSocket = nil;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if ([UserLocal isLogin] && !self.isBackgournd && self->_webSocket.readyState != SR_OPEN) {
            NSLog(@"重新连接socket");
            [self startWebSocket];
        }
    });
}
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean{
    NSLog(@"WebSocket 关闭");
    _webSocket = nil;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if ([UserLocal isLogin] && !self.isBackgournd && self->_webSocket.readyState != SR_OPEN) {
            NSLog(@"重新连接socket");
            [self startWebSocket];
        }
    });
}
//接受消息
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message{
    NSData *data_msg = [message dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *messageDic = [NSJSONSerialization JSONObjectWithData:data_msg options:NSJSONReadingMutableContainers error:nil];
    if ([messageDic[@"type"] integerValue] == MessageType) {
        NSString *strContent = messageDic[@"content"];
        SLLoanMessageModel *msgModel =   [SLLoanMessageModel mj_objectWithKeyValues:[self convert2DictionaryWithJSONString:strContent]];
        if (msgModel != nil) {
            [getDelegate() addLocalNotice:msgModel];
        }
//        NSString * reqId = messageDic[@"content"];
//        NSLog(@"消息回执%@",reqId);
//        void (^complete)(BOOL isSuccess) = [self.msgCompleteBlocks objectForKey:reqId];
//        if (complete) {
//            [self.msgCompleteBlocks removeObjectForKey:reqId];
//            complete(YES);
//        }
    }
//    if ([messageDic[@"packType"] integerValue] == ChatPackTypePong ) {
//        NSLog(@"WebSocket Pong");
//    }
}

- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload{
    debugLog(@"pong");
}

- (NSDictionary *)convert2DictionaryWithJSONString:(NSString *)jsonString{
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err){
        NSLog(@"%@",err);
        return nil;
    }
    return dic;
}

@end
